var formativeAssessmentViewModel = new FormativeAssessmentViewModel();
function bodyOnLoad() {
	ko.applyBindings(formativeAssessmentViewModel);
	jQuery('#dfaTitle102').text($('#className').val());
}

// -----------------------Binding For Tabs-------------------------
ko.bindingHandlers.jqTabs = {
	init : function(element, valueAccessor) {
		var options = valueAccessor() || {};
		setTimeout(function() {
			$(element).tabs(options);
		}, 1000);
	}
};

// -----------------------Binding For DatePicker-------------------------

ko.bindingHandlers.jqueryUIBindings = {
	init : function(element, valueAccessor) {
		console.log("::::");
		jQuery(element).datepicker({

			changeMonth : true,

			changeYear : true,

			dateFormat : "yy-mm-dd"

		});
	},
	update : function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
	}
};

//---------------------------------------------------------------------------------

function FormativeAssessmentViewModel() {

	var self = this;
	self.title = "Version New";
	self.windowMode = "";

	self.assessmentArr = ko.observableArray([]);
	self.label = ko.observable('dialog test');
	self.isOpen = ko.observable(false);
	self.currentContent = ko.observable();
	//drop down menus

	self.subSubjectsComboArr = ko.observableArray([]);
	self.toolsComboArr = ko.observableArray([]);
	self.techniquesComboArr = ko.observableArray([]);
	self.statusComboArr = ko.observableArray([]);

	//-----------------Loading Subjects JSON---------------------------------
	var dfaSubSubjectsJsonData = $.getJSON(parentUrl + PDB_GETSUBJECTSBYCLASS + classId, {
		returnformat : 'json'
	}, function(allData1) {
		var mappedSubSubjectsData = jQuery.map(allData1, function(item) {
			return new SubSubjectIds(item)
		});

		self.subSubjectsComboArr(mappedSubSubjectsData);
	});

	//-----------------Loading Tools JSON---------------------------------
	var dfaToolsJsonData = $.getJSON(parentUrl + PDB_GETTOOLSFORASSESS, {
		returnformat : 'json'
	}, function(allData3) {
		var mappedToolsData = jQuery.map(allData3, function(item) {
			return new ToolIds(item)
		});
		self.toolsComboArr(mappedToolsData);
	});
	dfaToolsJsonData.done(function() {//console.log( "second success" );
	})
	dfaToolsJsonData.fail(function() {// console.log( "error" );
	})
	dfaToolsJsonData.always(function() {//console.log( "--dfaToolsJsonData complete--" );
	});

	//-----------------Loading Techniques JSON---------------------------------
	var dfaTechniquesJsonData = $.getJSON(parentUrl + PDB_GETTECHNIQUESFORASSESS, {
		returnformat : 'json'
	}, function(allData4) {
		var mappedTechniquesData = jQuery.map(allData4, function(item) {
			return new TechniquesIds(item)
		});
		self.techniquesComboArr(mappedTechniquesData);
	});

	//-----------------Loading Status JSON---------------------------------

	var dfaStatusJsonData = $.getJSON('/ce-static-testedge/common/data/dfa_status.json', {
		returnformat : 'json'
	}, function(allData6) {
		console.log("here=======1====")
		var mappedStatusData = jQuery.map(allData6, function(item) {
			return new StatusVO(item)
		});

		self.statusComboArr(mappedStatusData);

	});

	// var dfaTabJsondata                     = $.getJSON('json/dfa_tab.json', {returnformat : 'json'}, function(allData) {
	// console.log(" self.assessmentArr", 1234)
	//---------------Loading Tabs Json Start--------------------------------------------
	var dfaTabJsondata = $.getJSON(parentUrl + PDB_GETSECFORMATIVEASSESSMENTS + classId, {
		returnformat : 'json'
	}, function(allData) {
		var mappedData = jQuery.map(allData, function(item) {
			return new FormativeAssessmentVO(item, self.subSubjectsComboArr(), self.toolsComboArr(), self.techniquesComboArr(), self.currentContent)
		});
		self.assessmentArr(mappedData);
		// console.log(" self.assessmentArr", self.assessmentArr)
	});
	dfaTabJsondata.done(function() {//console.log( "dfaTabJsondata second success" );
	})
	dfaTabJsondata.fail(function() {//console.log( "dfaTabJsondata error" );
	})
	dfaTabJsondata.always(function() {//console.log( "--dfaTabJsondata complete--" );
	});

	//console.log(" self.assessmentArr", 5678)
	//--------------hold the currently selected item-------------
	self.selectedItem = ko.observable();
	//--------------make edits to a copy-------------------------
	self.itemForEditing = ko.observable();

}

function loadCurrentTabData(_assessmentId, _arr, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent, chapterArr, _termId) {

	console.log("loadCurrentTabData---------------")
	//var baseUrl = "json/";
	//-----------------Loading Syllabus JSON---------------------------------
	var dfaSyllabusJsonData = $.getJSON(parentUrl + PDB_GETCURRPLANCHAPTERSFORTERM + termId + _termId, {
		returnformat : 'json'
	}, function(allData2) {
		var mappedSyllabusData = jQuery.map(allData2, function(item) {
			return new ChapterIds(item)
		});
		//  console.log("mappedSyllabusData",mappedSyllabusData)
		chapterArr(mappedSyllabusData);

	});
	dfaSyllabusJsonData.done(function() {
		console.log("dfaSyllabusJsonData second success");
	})
	dfaSyllabusJsonData.fail(function() {
		console.log("dfaSyllabusJsonData error");
	})
	dfaSyllabusJsonData.always(function() {
		console.log("--dfaSyllabusJsonData complete--");
	});

	console.log("_assessmentId---------", _assessmentId)

	var dfaContentJsonData = $.getJSON(parentUrl + PDB_GETSECFORMATIVEASSESSMENTTESTS + assessmentId + _assessmentId + classId, {
		returnformat : 'json'
	}, function(currentData) {
		var mappedcontentData = jQuery.map(currentData, function(item) {
			return new ContentModel(item, subSubjectsComboArr, toolsComboArr, techniquesComboArr)
		});
		_arr(mappedcontentData);
	});

}

function FormativeAssessmentVO(data, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent) {
	var self = this;

	self.sectionId = ko.observable();
	self.termId = ko.observable();
	self.termTitle = ko.observable();
	self.assessmentId = ko.observable();
	self.assessmentTitle = ko.observable();
	self.tests = ko.observableArray([]);
	self.tests.selectedItem = ko.observable();
	self.tests.currentContent = ko.observable();
	self.itemForEditing = ko.observable();
	self.chapterArr = ko.observableArray([]);
	self.termTitle.activateTab = ko.observable();
	self.cache = function() {
	};
	self.update(data, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent)

	self.changeTabModel = function() {
		if (!self.termTitle.activateTab()) {
			//console.log("self.termId()",self.termId())
			loadCurrentTabData(self.assessmentId(), self.tests, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent, self.chapterArr, self.termId())
			self.termTitle.activateTab(true)
		}
		currentContent(self);
	}

	self.openSyllabusDialog = function() {
		//console.log("self.chapterArr.length",self.chapterArr().length);

		for (var i = 0; i < self.chapterArr().length; i++) {
			if (this.syllabus().indexOf(self.chapterArr()[i].chapterId()) > -1) {
				self.chapterArr()[i].chapterTitle.isSelected(true);
				//console.log(" self.chapterArr()[i].chapterTitle.isSelected", self.chapterArr()[i].chapterTitle.isSelected());
			} else {
				self.chapterArr()[i].chapterTitle.isSelected(false);
			}
		}

		self.tests.currentContent(this)
		var chapterDialog = $("#chapters").dialog("open");
		chapterDialog.dialog("option", "position", "center");
		//console.log("openSyllabusDialog",this);
	}
	self.saveSyllabus = function() {
		var tempSyllabus = "";
		for (var i = 0; i < self.chapterArr().length; i++) {
			//console.log("self.chapterArr()[i].chapterId()",self.chapterArr()[i].chapterId());
			if (self.chapterArr()[i].chapterTitle.isSelected()) {
				tempSyllabus += self.chapterArr()[i].chapterId() + ",";
				//console.log(" self.chapterArr()[i].chapterTitle.isSelected", self.chapterArr()[i].chapterTitle.isSelected());
			}
		}
		tempSyllabus = tempSyllabus.replace(/\,$/, '');
		//console.log("this.tempSyllabus()",tempSyllabus);
		self.tests.currentContent().syllabus(tempSyllabus);
		$("#chapters").dialog("close");
	}
	self.CancelSyllabusDialog = function() {
		$("#chapters").dialog("close");
	}

	self.addAssessmentModel = function() {
		self.windowMode = "add";
		this.itemForEditing(new ContentModel({
			testTitle : "",
			subjectId : "",
			toolId : "",
			techniqueId : "",
			subjectTitle : "",
			testDate : "",
			gradeClassId : "",
			testId : "",
			syllabus : "",
			testStatus : 2,
			testTotalMarks : "",
			gradeClassId : currentClassId,
			assessmentId : self.assessmentId()
		}, subSubjectsComboArr, toolsComboArr, techniquesComboArr));

		var addTestDialog = $("#add-Test").dialog("open");
		addTestDialog.dialog("option", "position", "center");
		var vm1 = ko.validation.group(self.itemForEditing());
		vm1.showAllMessages(false);
	}
	self.cancelAddAssessment = function() {
		$("#add-Test").dialog("close");
	}
	self.openAssessmentForEditing = function(item) {
		//console.log("openAssessmentForEditing");
		self.windowMode = "edit";
		self.selectItem(item, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent);
		$("#add-Test").dialog("open");
	}

	self.saveAssessmentModel = function() {
		var vm = ko.validation.group(self.itemForEditing());
		if (self.itemForEditing().isValid() == false) {
			vm.showAllMessages(true);
			alert("Please fill all Required fields before saving.");
			return;
		}

		var mapping = {
			'ignore' : ["errors"]
		};
		var saveDataStr = ko.mapping.toJS(self.itemForEditing(), mapping);
		//saveDataStr = JSON.stringify(ko.toJS(saveDataStr), null, 2)
		// console.log("currentContent \n", saveDataStr);
		// saveAssessmentModelToServer(saveDataStr)

		var saveDataStr = JSON.stringify(ko.toJS(saveDataStr), null, 2);
		console.log("saveDataStr \n", saveDataStr);
		saveAssessmentModelToServer(saveDataStr, self.addedAssessmentModelFromServer);
	}

	self.addedAssessmentModelFromServer = function(data) {
		var newAssessmentModel;
		if (self.windowMode == "add") {
			newAssessmentModel = new ContentModel(data, subSubjectsComboArr, toolsComboArr, techniquesComboArr)
			self.tests.push(newAssessmentModel);
		} else {
			self.acceptItem(null);
		}
		//---------------------IF IGNORE IS REQUIRED------------------------------
		// var mapping = {'ignore': ["itemForEditing", "chapterArr","windowMode"]};
		// var saveDataStr = ko.mapping.toJS(self, mapping);
		//saveDataStr = JSON.stringify(ko.toJS(saveDataStr), null, 2)
		// console.log("currentContent \n", saveDataStr);
		// saveAssessmentModelToServer(saveDataStr)
		self.itemForEditing(null);
		$("#add-Test").dialog("close");
	}

	self.openDeleteAssessmentDialog = function(item) {
		//console.log("dialog-confirm1");
		self.tests.selectedItem(item, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent);
		$("#dialog-confirm1").dialog("open");
	}
	self.deleteAssessment = function(item) {
		console.log("deleteAssessment", self.tests.selectedItem().testId());

		var deleteAssessmentData = $.getJSON(parentUrl + PDB_DELETESECFORMATIVEASSESSMENTTEST + testId + self.tests.selectedItem().testId(), {
			returnformat : 'json'
		});
		deleteAssessmentData.done(function() {
			console.log("DELETE second success");
		})
		deleteAssessmentData.fail(function() {
			console.log("DELETE ERROR");
		})
		deleteAssessmentData.always(function() {
			console.log("--DELETE COMPLETE--");
		});

		self.tests.remove(self.tests.selectedItem());
		$("#dialog-confirm1").dialog("close");
	}
	self.cancelDeleteDialog = function() {
		$("#dialog-confirm1").dialog("close");
	}
	if (!firstloadBool) {
		loadCurrentTabData(self.assessmentId(), self.tests, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent, self.chapterArr, self.termId())
		self.termTitle.activateTab(true)
		currentContent(self);
		firstloadBool = true;
	}

}

ko.utils.extend(FormativeAssessmentVO.prototype, {
	update : function(data, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent) {
		this.sectionId(data.sectionId || "");
		this.termId(data.termId || "");
		this.termTitle(data.termTitle || "");
		this.assessmentId(data.assessmentId || "");
		this.assessmentTitle(data.assessmentTitle || "");

		//console.log("ko.utils.extend(FormativeAssessmentVO.prototype||subSubjectsComboArr",subSubjectsComboArr);

		if (data.tests) {
			var mappedContentData = jQuery.map(data.tests, function(item) {
				return new ContentModel(item, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent)
			});
			this.tests(mappedContentData);

			//save off the latest data for later use
			this.cache.latestData = data;
		}
	},
	//select an item and make a copy of it for editing
	selectItem : function(item, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent) {
		this.tests.selectedItem(item, subSubjectsComboArr, toolsComboArr, techniquesComboArr, currentContent);
		this.itemForEditing(new ContentModel(ko.toJS(item), subSubjectsComboArr, toolsComboArr, techniquesComboArr));
	},

	acceptItem : function(item) {
		var selected = this.tests.selectedItem(), edited = ko.toJS(this.itemForEditing());
		//clean copy of edited
		// console.log(edited)
		//apply updates from the edited item to the selected item
		selected.update(edited);

		//clear selected item
		this.tests.selectedItem(null);
		this.itemForEditing(null);
	},

	//just throw away the edited item and clear the selected observables
	revertItem : function() {
		this.tests.selectedItem(null);
		this.itemForEditing(null);
		this.update(this.cache.latestData);
	}
});

ko.utils.extend(FormativeAssessmentViewModel.prototype, {

});

ko.utils.extend(ContentModel.prototype, {
	update : function(data, subSubjectsComboArr, toolsComboArr, techniquesComboArr) {
		this.testTitle(data.testTitle || "");
		this.subjectId(data.subjectId || "");
		this.toolId(data.toolId || "");
		this.techniqueId(data.techniqueId || "");
		this.subjectTitle(data.subjectTitle || "");
		this.testDate(data.testDate || "");
		this.tests([] || "");
		this.gradeClassId(data.gradeClassId || "");
		this.assessmentId(data.assessmentId || "");
		this.syllabus(data.syllabus || "");
		this.testStatus(data.testStatus || "");
		this.testTotalMarks(data.testTotalMarks || "");

		//save off the latest data for later use
		//this.cache.latestData = data;

	},
	revertItem : function() {
		//this.update(this.cache.latestData);
	}
});

function StatusVO(data) {
	this.testStatus = ko.observable(data.testStatus);
	this.statusTitle = ko.observable(data.statusTitle);

}

function ChapterIds(data) {
	this.chapterId = ko.observable(data.chapterId);
	this.chapterTitle = ko.observable(data.chapterTitle);
	this.chapterTitle.isSelected = ko.observable(false);
	//console.log(" this.chapterTitle.isSelected ", this.chapterTitle.isSelected() )

}

function SubSubjectIds(data) {
	this.subjectId = ko.observable(data.subuid);
	this.subjectTitle = ko.observable(data.title);
}

function ToolIds(data) {
	this.toolId = ko.observable(data.toolTechId);
	this.title = ko.observable(data.title);
}

function TechniquesIds(data) {
	this.techniqueId = ko.observable(data.toolTechId);
	this.title = ko.observable(data.title);
}

function ContentModel(data, subSubjectsComboArr, toolsComboArr, techniquesComboArr) {
	var self = this;
	self.testTitle = ko.observable(data.testTitle).extend({
		required : true
	});
	self.testDate = ko.observable(data.testDate).extend({
		required : true,
		date : true
	});
	self.testTotalMarks = ko.observable(data.testTotalMarks).extend({
		required : true,
		min : 0
	});
	self.subjectId = ko.observable(data.subjectId).extend({
		required : true
	});
	self.toolId = ko.observable(data.toolId).extend({
		required : true
	});
	self.techniqueId = ko.observable(data.techniqueId).extend({
		required : true
	});
	self.subjectTitle = ko.observable(data.subjectTitle);
	self.tests = ko.observableArray([]);
	self.gradeClassId = ko.observable(data.gradeClassId);
	self.assessmentId = ko.observable(data.assessmentId);
	self.testId = ko.observable(data.testId);
	self.syllabus = ko.observable(data.syllabus).extend({
		required : true
	});
	self.testStatus = ko.observable(data.testStatus);

	self.update(data, subSubjectsComboArr, toolsComboArr, techniquesComboArr)

	self.subjectId.title = ko.computed(function() {
		var _subjectTitle
		var subjectTitle = ko.utils.arrayForEach(subSubjectsComboArr, function(item) {
			if (item.subjectId() == self.subjectId()) {
				_subjectTitle = item.subjectTitle();
			}
		});
		return _subjectTitle;

	}, this);

	self.toolId.title = ko.computed(function() {
		var _toolTitle
		var toolTitle = ko.utils.arrayForEach(toolsComboArr, function(item) {
			if (item.toolId() == self.toolId()) {
				_toolTitle = item.title();
			}
		});
		return _toolTitle;
	}, this);

	self.techniqueId.title = ko.computed(function() {
		var _techniqueTitle
		var techniqueTitle = ko.utils.arrayForEach(techniquesComboArr, function(item) {
			if (item.techniqueId() == self.techniqueId()) {
				//     console.log("item.title()",item.title())
				_techniqueTitle = item.title();
			}
		});
		//  console.log("techniqueTitle",_techniqueTitle)
		return _techniqueTitle;
	}, this);

	self.syllabus.count = ko.computed(function() {
		return (self.syllabus().split(",").length )
	}, this);

	self.onComboChange = function(item) {
		// console.log("onComboChange",item.testStatus());

		var saveDataStr = JSON.stringify(ko.toJS(self), null, 2);
		console.log("onComboChange \n", saveDataStr);
		saveAssessmentModelToServer(saveDataStr, self.doNothing);
	}
	self.doNothing = function() {
	}
}

function jsonIOError(exp) {
	console.log("jsonIOError", exp);
}

ko.bindingHandlers.uniqueId = {
	init : function(element, valueAccessor) {
		var value = valueAccessor();
		value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);

		element.id = value.id;
	},
	counter : 0,
	prefix : "unique"
};

ko.bindingHandlers.uniqueFor = {
	init : function(element, valueAccessor) {
		var value = valueAccessor();
		value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);

		element.setAttribute("for", value.id);
	}
};

function saveAssessmentModelToServer(dataStr, callBackfunction) {

	var localData = {
		"savedata" : dataStr
	};
	$.ajax({
		url : parentUrl + PDB_SAVESECFORMATIVEASSESSMENTTESTS,
		type : 'POST',
		data : localData,
		dataType : 'json',
		async : false,
		success : function(msg) {
			callBackfunction(msg);
			console.log(msg, " Save Operation copmpleted")
		},
		error : jsonIOError
	});
}

